package com.sidianzhong.sdz.controller;

import com.alibaba.fastjson.JSONObject;
import com.sidianzhong.sdz.annotation.BackLoginToken;
import com.sidianzhong.sdz.annotation.UserLoginToken;
import com.sidianzhong.sdz.model.*;
import com.sidianzhong.sdz.model.commond.UserToken;
import com.sidianzhong.sdz.service.*;
import com.sidianzhong.sdz.service.commond.RedisService;
import com.sidianzhong.sdz.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * Created by hxg on 2016/10/06.
 */
@Api(description = "贷款资格")
@Controller
public class LoansAttestationController {

    @Autowired
    LoansAttestationService loansAttestationService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;
    @Autowired
    UserWalletService userWalletService;
    @Autowired
    ConstantService constantService;

    @BackLoginToken
    @ApiOperation(value = "创建'贷款资格'表中一条信息")
    @RequestMapping(value = "/loansAttestation/new", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object createLoansAttestation(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "authPrice", required = false) Double authPrice,
            @RequestParam(value = "limits", required = false) Double limits,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "creditStatus", required = false) Integer creditStatus,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        LoansAttestation item = new LoansAttestation();
        Date date = new Date();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (authPrice != null) {
            item.setAuthPrice(authPrice);
        }
        if (limits != null) {
            item.setLimits(limits);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (creditStatus != null) {
            item.setCreditStatus(creditStatus);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setCreateTime(new Date());
        item.setLastUpdateTime(new Date());
        LoansAttestation iteams = loansAttestationService.create(item);
        boolean result = iteams != null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "删除'贷款资格'表中的某条记录")
    @RequestMapping(value = "/loansAttestation/delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object deleteLoansAttestation(
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id
    ) {
        LoansAttestation item = loansAttestationService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        int delete = loansAttestationService.delete(id);
        boolean result = delete != 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "修改'贷款资格'表中的某条记录")
    @RequestMapping(value = "/loansAttestation/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object editLoansAttestation(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "authPrice", required = false) Double authPrice,
            @RequestParam(value = "limits", required = false) Double limits,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "creditStatus", required = false) Integer creditStatus,
            @RequestParam(value = "status", required = false) Integer status
    ) {
        LoansAttestation item = loansAttestationService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        if (userId != null) {
            item.setUserId(userId);
        }
        if (authPrice != null) {
            item.setAuthPrice(authPrice);
        }
        if (limits != null) {
            item.setLimits(limits);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (creditStatus != null) {
            item.setCreditStatus(creditStatus);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setLastUpdateTime(new Date());
        int update = loansAttestationService.update(item);
        boolean result = update != 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'贷款资格'表中的某条记录")
    @RequestMapping(value = "/getLoansAttestationById", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getLoansAttestationById(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id
    ) {
        LoansAttestation item = loansAttestationService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResultModel.ok(item), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'贷款资格'表中的多条记录返回对象")
    @RequestMapping(value = "/loansAttestations", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getLoansAttestations(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "authPrice", required = false) Double authPrice,
            @RequestParam(value = "limits", required = false) Double limits,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "creditStatus", required = false) Integer creditStatus,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        LoansAttestation item = new LoansAttestation();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (authPrice != null) {
            item.setAuthPrice(authPrice);
        }
        if (limits != null) {
            item.setLimits(limits);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (creditStatus != null) {
            item.setCreditStatus(creditStatus);
        }
        if (status != null) {
            item.setStatus(status);
        }
        if (createTime != null) {
            item.setCreateTime(Tools.convertStringToDate(createTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (lastUpdateTime != null) {
            item.setLastUpdateTime(Tools.convertStringToDate(lastUpdateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        PageInfo<LoansAttestation> list = loansAttestationService.getListWithPaging(pageNum, pageSize, sortItem, sortOrder, item);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'贷款资格'表中的多条记录返回自定义JSONObject")
    @RequestMapping(value = "/loansAttestationsObject", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getLoansAttestationsObject(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "authPrice", required = false) Double authPrice,
            @RequestParam(value = "limits", required = false) Double limits,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "creditStatus", required = false) Integer creditStatus,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        LoansAttestation item = new LoansAttestation();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (authPrice != null) {
            item.setAuthPrice(authPrice);
        }
        if (limits != null) {
            item.setLimits(limits);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (creditStatus != null) {
            item.setCreditStatus(creditStatus);
        }
        if (status != null) {
            item.setStatus(status);
        }
        if (createTime != null) {
            item.setCreateTime(Tools.convertStringToDate(createTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (lastUpdateTime != null) {
            item.setLastUpdateTime(Tools.convertStringToDate(lastUpdateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        PageInfo<JSONObject> list = loansAttestationService.getListWithObject(pageNum, pageSize, sortItem, sortOrder, item);
        List<JSONObject> list1 = list.getList();
        List<JSONObject> collect = list1.stream().map(ls -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", ls.getInteger("id"));
            jsonObject.put("userId", ls.getInteger("userId"));
            jsonObject.put("authPrice", ls.getDouble("authPrice"));
            jsonObject.put("limits", ls.getDouble("limits"));
            jsonObject.put("coinId", ls.getInteger("coinId"));
            jsonObject.put("creditStatus", ls.getInteger("creditStatus"));
            jsonObject.put("status", ls.getInteger("status"));
            jsonObject.put("createTime", ls.getDate("createTime"));
            jsonObject.put("lastUpdateTime", ls.getDate("lastUpdateTime"));
            return jsonObject;
        }).collect(Collectors.toList());
        list.setList(collect);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "激活信用额度")
    @RequestMapping(value = "/activationLoans",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object activationLoans(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "payPassword") String payPassword,
            @RequestParam(value = "code") String code
    ) {

        ResourceBundle myResourcesBundle = International.getLanguage(request);
        Integer user_id = (Integer) request.getAttribute("USER_ID");
        LoansAttestation byUser = loansAttestationService.getByUser(user_id);
        if (byUser != null) {
            return new ResponseEntity<>(ResultModel.ok(false), HttpStatus.OK);
        }
        User user = userService.get(user_id);


//        if (code == null || code.isEmpty() || !code.matches(Matches.PHONE_CODE_MATCHES) || !code.equals(redisService.getCode(user.getPhone()).getCode())) {
//            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "smsCodeError"), HttpStatus.OK);
//        }
//        if (payPassword == null || payPassword.isEmpty() || !payPassword.equals(user.getPayPassword())) {
//            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "payPasswordError"), HttpStatus.OK);
//        }
        Integer usdtId = 10000001;
        Double aDouble = Double.valueOf(constantService.selectValueByKey(Constants.LOANS_AMOUNT));
        Double aDouble1 = Double.valueOf(constantService.selectValueByKey(Constants.AMOUNT_RATIO));

        UserWallet userWalletUSDT = userWalletService.getByUserId(user_id, usdtId);
        if (userWalletUSDT.getAmount() - aDouble < 0) {
            return new ResponseEntity<>(ResultModel.error(myResourcesBundle, "changeMaxError"), HttpStatus.OK);
        }
        Date date = new Date();
        LoansAttestation loansAttestation = new LoansAttestation();
        loansAttestation.setUserId(user_id);
        loansAttestation.setAuthPrice(aDouble);
        loansAttestation.setLimits(0.0);
        loansAttestation.setCoinId(usdtId);
        loansAttestation.setCreditStatus(0);
        loansAttestation.setStatus(0);
        loansAttestation.setCreateTime(date);
        loansAttestation.setLastUpdateTime(date);
        LoansAttestation loansAttestation1 = loansAttestationService.create(loansAttestation);
        if (loansAttestation1 != null) {
            userWalletUSDT.setAmount(userWalletUSDT.getAmount() - aDouble);
            userWalletUSDT.setLastUpdateTime(date);
            userWalletService.update(userWalletUSDT);
            int i = loansAttestationService.updateLpans(user_id, aDouble * aDouble1, date, user_id);
        }
        return new ResponseEntity<>(ResultModel.ok(true), HttpStatus.OK);
    }
}
